#!/usr/bin/Python
import signal, time, sys, multiprocessing, traceback, os, threading
sys.path.append('..')
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from bdp.i_crawler.i_downloader import DownloadService
import pytoml
import getopt
from DownloadService import DownloaderServer
from DownloaderHandle import DownloadHandler
from handler import DownloadHandler as handle
from i_util.logs import LogHandler
from download_proccessor import DownloaderProccessor
from i_util.ProfilingUtil import profiling_signal_handler

def main(conf):
    signal.signal(signal.SIGTERM, signal.SIG_DFL)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    signal.signal(signal.SIGUSR1, lambda a, b: profiling_signal_handler("downloader", a, b))

    download_hanler = handle(conf)
    handler = DownloadHandler(download_hanler,conf)
    download_server = DownloaderServer(conf,handler)
    download_server.start()

    try:
        processor = DownloadService.Processor(handler)
        transport = TSocket.TServerSocket(port=conf['server'].get('port'))
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
        server.setNumThreads(conf['server'].get('server_thread_num'))
        server.serve()
    except Exception as e:
        conf.get('log').error(e.message)
        download_server.stop("failt")
        os._exit(1)
    download_server.stop("success")

def usaget():
    pass
if __name__ == '__main__':
    try:
        file_path='./downloader.toml'
        opt,args=getopt.getopt(sys.argv[1:],'f:',['help'])
        for name,value in opt:
            if name == "-f":
                file_path=value
            elif name in ("-h", "--help"):
                usaget()
                sys.exit()
            else:
                assert False, "unhandled option"
        with open(file_path, 'rb') as config:
            config = pytoml.load(config)
        logger_name = config["server"].get('name') + str(config["server"].get('port'))
        print logger_name
        config['log']=LogHandler(logger_name)
        main(config)
    except getopt.GetoptError:
        sys.exit()

